package controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import util.DBUtil;

@WebServlet("/updateMemberGroup")
public class UpdateMemberGroupServlet extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置请求和响应的字符编码为 UTF-8
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=UTF-8");

        PrintWriter out = response.getWriter();
        ObjectMapper mapper = new ObjectMapper();
        ObjectNode jsonResponse = mapper.createObjectNode();

        String memberId = request.getParameter("id");
        String newGroupId = request.getParameter("groupId");

        if (memberId == null || memberId.isEmpty() || newGroupId == null || newGroupId.isEmpty()) {
            jsonResponse.put("message", "成员ID和新组别ID不能为空");
            out.print(mapper.writeValueAsString(jsonResponse));
            return;
        }

        Connection connection = null;
        PreparedStatement preparedStatement = null;

        try {
            connection = DBUtil.getConnection();
            String updateSQL = "UPDATE users SET group_id = ? WHERE id = ?";
            preparedStatement = connection.prepareStatement(updateSQL);
            preparedStatement.setInt(1, Integer.parseInt(newGroupId));
            preparedStatement.setInt(2, Integer.parseInt(memberId));

            int rowsAffected = preparedStatement.executeUpdate();
            if (rowsAffected > 0) {
                jsonResponse.put("message", "成员组别更新成功");
            } else {
                jsonResponse.put("message", "成员组别更新失败，可能不存在该成员");
            }
            out.print(mapper.writeValueAsString(jsonResponse));
        } catch (SQLException e) {
            jsonResponse.put("message", "更新成员组别时发生错误");
            out.print(mapper.writeValueAsString(jsonResponse));
            e.printStackTrace();
        } finally {
            DBUtil.close(connection, preparedStatement, null);
        }
    }
}
